{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "\n",
    "xla_flags = os.environ.get(\"XLA_FLAGS\", \"\")\n",
    "xla_flags += \" --xla_gpu_triton_gemm_any=True\"\n",
    "os.environ[\"XLA_FLAGS\"] = xla_flags\n",
    "os.environ[\"XLA_PYTHON_CLIENT_PREALLOCATE\"] = \"false\"\n",
    "os.environ[\"MUJOCO_GL\"] = \"egl\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import functools\n",
    "import json\n",
    "import pickle\n",
    "from datetime import datetime\n",
    "\n",
    "import jax\n",
    "import mediapy as media\n",
    "import mujoco\n",
    "import numpy as np\n",
    "from brax.training.agents.ppo import networks as ppo_networks\n",
    "from brax.training.agents.ppo import train as ppo\n",
    "from etils import epath\n",
    "from flax.training import orbax_utils\n",
    "from orbax import checkpoint as ocp\n",
    "\n",
    "from mujoco_playground import registry, wrapper\n",
    "from mujoco_playground.config import locomotion_params\n",
    "from mujoco_playground.experimental.utils.plotting import TrainingPlotter\n",
    "\n",
    "# Enable persistent compilation cache.\n",
    "jax.config.update(\"jax_compilation_cache_dir\", \"/tmp/jax_cache\")\n",
    "jax.config.update(\"jax_persistent_cache_min_entry_size_bytes\", -1)\n",
    "jax.config.update(\"jax_persistent_cache_min_compile_time_secs\", 0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "env_name = \"ApolloJoystickFlatTerrain\"\n",
    "env_cfg = registry.get_default_config(env_name)\n",
    "randomizer = registry.get_domain_randomizer(env_name)\n",
    "ppo_params = locomotion_params.brax_ppo_config(env_name)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "env_cfg.reward_config.scales.energy = -1e-5\n",
    "env_cfg.reward_config.scales.action_rate = -1e-3\n",
    "env_cfg.reward_config.scales.torques = 0.0\n",
    "\n",
    "env_cfg.noise_config.level = 0.0  # 1.0\n",
    "env_cfg.push_config.enable = True\n",
    "env_cfg.push_config.magnitude_range = [0.1, 2.0]\n",
    "\n",
    "ppo_params.num_timesteps = 150_000_000\n",
    "ppo_params.num_evals = 15"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "SUFFIX = None\n",
    "FINETUNE_PATH = None\n",
    "\n",
    "# Generate unique experiment name.\n",
    "now = datetime.now()\n",
    "timestamp = now.strftime(\"%Y%m%d-%H%M%S\")\n",
    "exp_name = f\"{env_name}-{timestamp}\"\n",
    "if SUFFIX is not None:\n",
    "  exp_name += f\"-{SUFFIX}\"\n",
    "print(f\"{exp_name}\")\n",
    "\n",
    "# Possibly restore from the latest checkpoint.\n",
    "if FINETUNE_PATH is not None:\n",
    "  FINETUNE_PATH = epath.Path(FINETUNE_PATH)\n",
    "  latest_ckpts = list(FINETUNE_PATH.glob(\"*\"))\n",
    "  latest_ckpts = [ckpt for ckpt in latest_ckpts if ckpt.is_dir()]\n",
    "  latest_ckpts.sort(key=lambda x: int(x.name))\n",
    "  latest_ckpt = latest_ckpts[-1]\n",
    "  restore_checkpoint_path = latest_ckpt\n",
    "  print(f\"Restoring from: {restore_checkpoint_path}\")\n",
    "else:\n",
    "  restore_checkpoint_path = None"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "ckpt_path = epath.Path(\"checkpoints\").resolve() / exp_name\n",
    "ckpt_path.mkdir(parents=True, exist_ok=True)\n",
    "print(f\"{ckpt_path}\")\n",
    "\n",
    "with open(ckpt_path / \"config.json\", \"w\") as fp:\n",
    "  json.dump(env_cfg.to_json(), fp, indent=4)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plotter = TrainingPlotter(max_timesteps=ppo_params.num_timesteps, figsize=(15, 10))\n",
    "\n",
    "\n",
    "def progress(num_steps, metrics):\n",
    "  plotter.update(num_steps, metrics)\n",
    "\n",
    "\n",
    "def policy_params_fn(current_step, make_policy, params):\n",
    "  del make_policy  # Unused.\n",
    "  orbax_checkpointer = ocp.PyTreeCheckpointer()\n",
    "  save_args = orbax_utils.save_args_from_target(params)\n",
    "  path = ckpt_path / f\"{current_step}\"\n",
    "  orbax_checkpointer.save(path, params, force=True, save_args=save_args)\n",
    "\n",
    "\n",
    "training_params = dict(ppo_params)\n",
    "del training_params[\"network_factory\"]\n",
    "\n",
    "train_fn = functools.partial(\n",
    "  ppo.train,\n",
    "  **training_params,\n",
    "  network_factory=functools.partial(\n",
    "    ppo_networks.make_ppo_networks, **ppo_params.network_factory\n",
    "  ),\n",
    "  restore_checkpoint_path=restore_checkpoint_path,\n",
    "  progress_fn=progress,\n",
    "  wrap_env_fn=wrapper.wrap_for_brax_training,\n",
    "  policy_params_fn=policy_params_fn,\n",
    "  randomization_fn=randomizer,\n",
    ")\n",
    "\n",
    "env = registry.load(env_name, config=env_cfg)\n",
    "eval_env = registry.load(env_name, config=env_cfg)\n",
    "make_inference_fn, params, _ = train_fn(environment=env, eval_env=eval_env)\n",
    "if len(plotter.times) > 1:\n",
    "  print(f\"time to jit: {plotter.times[1] - plotter.times[0]}\")\n",
    "  print(f\"time to train: {plotter.times[-1] - plotter.times[1]}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "inference_fn = make_inference_fn(params, deterministic=True)\n",
    "jit_inference_fn = jax.jit(inference_fn)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Save normalizer and policy params to the checkpoint dir.\n",
    "normalizer_params, policy_params, value_params = params\n",
    "with open(ckpt_path / \"params.pkl\", \"wb\") as f:\n",
    "  data = {\n",
    "    \"normalizer_params\": normalizer_params,\n",
    "    \"policy_params\": policy_params,\n",
    "    \"value_params\": value_params,\n",
    "  }\n",
    "  pickle.dump(data, f)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [],
   "source": [
    "from mujoco_playground._src.gait import draw_joystick_command\n",
    "\n",
    "eval_env = registry.load(env_name, config=env_cfg)\n",
    "jit_reset = jax.jit(eval_env.reset)\n",
    "jit_step = jax.jit(eval_env.step)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "rng = jax.random.PRNGKey(12345)\n",
    "rollout = []\n",
    "modify_scene_fns = []\n",
    "state = jit_reset(rng)\n",
    "for i in range(env_cfg.episode_length):\n",
    "  act_rng, rng = jax.random.split(rng)\n",
    "  ctrl, _ = jit_inference_fn(state.obs, act_rng)\n",
    "  state = jit_step(state, ctrl)\n",
    "  if state.done:\n",
    "    print(\"something bad happened\")\n",
    "    break\n",
    "  rollout.append(state)\n",
    "  xyz = np.array(state.data.xpos[eval_env.mj_model.body(\"torso_link\").id])\n",
    "  xyz += np.array([0, 0.0, 0])\n",
    "  x_axis = state.data.xmat[eval_env._torso_body_id, 0]\n",
    "  yaw = -np.arctan2(x_axis[1], x_axis[0])\n",
    "  modify_scene_fns.append(\n",
    "    functools.partial(\n",
    "      draw_joystick_command,\n",
    "      cmd=state.info[\"command\"],\n",
    "      xyz=xyz,\n",
    "      theta=yaw,\n",
    "      scl=np.linalg.norm(state.info[\"command\"]),\n",
    "    )\n",
    "  )"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "render_every = 2\n",
    "fps = 1.0 / eval_env.dt / render_every\n",
    "print(f\"fps: {fps}\")\n",
    "traj = rollout[::render_every]\n",
    "mod_fns = modify_scene_fns[::render_every]\n",
    "\n",
    "scene_option = mujoco.MjvOption()\n",
    "scene_option.geomgroup[2] = True\n",
    "scene_option.geomgroup[3] = False\n",
    "scene_option.flags[mujoco.mjtVisFlag.mjVIS_CONTACTPOINT] = True\n",
    "scene_option.flags[mujoco.mjtVisFlag.mjVIS_CONTACTFORCE] = False\n",
    "scene_option.flags[mujoco.mjtVisFlag.mjVIS_TRANSPARENT] = False\n",
    "scene_option.flags[mujoco.mjtVisFlag.mjVIS_PERTFORCE] = False\n",
    "\n",
    "frames = eval_env.render(\n",
    "  traj,\n",
    "  camera=\"track\",\n",
    "  scene_option=scene_option,\n",
    "  width=640,\n",
    "  height=480,\n",
    "  modify_scene_fns=mod_fns,\n",
    ")\n",
    "media.show_video(frames, fps=fps, loop=False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
